﻿using System.Collections.Generic;
using Infrastructure.Lgd.Interfaces;
using NGenerics.DataStructures;
using VirtuosoDal.Repositories.RdfRepositories.Interfaces.Lgd;
using VirtuosoDal.Repositories.RdfRepositories.Lgd;

namespace Infrastructure.Lgd
{
   public class LgdTreeBuilder : ILgdTreeBuilder
   {
      private ILgdSchemaRepository _lgdSchemaRepository;

      public LgdTreeBuilder(LgdSchemaRepository lgdSchemaRepository)
      {
         _lgdSchemaRepository = lgdSchemaRepository;
      }

      public GeneralTree<string> GetCategoriesTree()
      {
         var categoriesTree = new GeneralTree<string>(null);

         GetCategoriesTreeInternal(categoriesTree, categoriesTree);

         return categoriesTree;
      }

      private void GetCategoriesTreeInternal(GeneralTree<string> categoriesTree, GeneralTree<string> parentNode)
      {
         List<string> childCategories = null;
         childCategories = parentNode.Data == null ? _lgdSchemaRepository.GetRootCategories() :
            _lgdSchemaRepository.GetChildCategories(parentNode.Data);

         foreach (string childCategory in childCategories)
         {
            //Is not null if the node is placed into several places of the tree
            GeneralTree<string> theSameNode = categoriesTree.FindNode(s => s == childCategory);

            if (theSameNode == null)
            {
               var childCategoryNode = new GeneralTree<string>(childCategory);
               parentNode.Add(childCategoryNode);

               GetCategoriesTreeInternal(categoriesTree, childCategoryNode);
            }
         }
      }
   }
}
